package com.xingxin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingxin.config.TokenTools;
import com.xingxin.entity.Manager;
import com.xingxin.service.ManagerService;
import com.xingxin.utils.ResultUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author mrLiu
 * @since 2021-01-08
 */
@RestController
@RequestMapping("/manager")
public class ManagerController {
    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private ManagerService managerService;

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestBody Map<String, Object> inMap) {
        logger.info("==>ManagerController--login()--start,params is:{}", inMap);
        Map<String, Object> data = new HashMap<>();
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> resultMap;
        if (CollectionUtils.isEmpty(inMap)) {
            resultMap = ResultUtils.resultMap("-1", "入参为空", null);
            logger.info("==>ManagerController--login()--over,result is:{}", resultMap);
            return resultMap;
        }
        try {
            map.put("mg_name", inMap.get("username"));
            map.put("mg_pwd", inMap.get("password"));
            List<Manager> managers = managerService.listByMap(map);
            if (CollectionUtils.isEmpty(managers)) {
                resultMap = ResultUtils.resultMap("-1", "用户名或者密码错误!", null);
                logger.info("==>ManagerController--login()--over,result is:{}", resultMap);
                return resultMap;
            }
            if (StringUtils.equals(managers.get(0).getMgName(), (String) inMap.get("username"))
                    && StringUtils.equals(managers.get(0).getMgPwd(), (String) inMap.get("password"))) {
                data.put("manager", managers.get(0));
                data.put("token", TokenTools.sign(managers.get(0).getMgName(),
                        String.valueOf(managers.get(0).getMgId())));
                resultMap = ResultUtils.resultMap("0", "success", data);
                logger.info("==>ManagerController--login()--over,result is:{}", resultMap);
                return resultMap;
            }
        } catch (Exception e) {
            logger.error("==>ManagerController--login()--Exception,result is:{}", e);
            return ResultUtils.resultMap("-1", "服务器异常", null);
        }
        return null;
    }

    /**
     * 查询管理员列表
     *
     * @param inMap
     * @return
     */
    @PostMapping("/selectAll")
    @ResponseBody
    public Map<String, Object> selectManagerList(@RequestBody Map<String, Object> inMap) {
        logger.info("==>ManagerController--selectManagerList--start,params is:{}", inMap);
        Map<String, Object> resultMap;
        try {
            Integer pageSize = Integer.parseInt(Optional.ofNullable(inMap.get("pageSize")).orElse("10").toString());
            Integer pageNo = Integer.parseInt(Optional.ofNullable(inMap.get("pageNo")).orElse("1").toString());
            //mybatis plus 分页查询
            Page<Manager> page = new Page<>(pageNo, pageSize);
            QueryWrapper<Manager> wrapper = new QueryWrapper<>();
            Page<Manager> data = managerService.page(page, wrapper);

            //过滤信息
            if (StringUtils.isNotBlank((String) inMap.get("query"))) {
                List<Manager> newList = data.getRecords().stream()
                        .filter(manager -> manager.getMgName().contains((String) inMap.get("query")))
                        .collect(Collectors.toList());
                data.setRecords(newList);
                data.setTotal(newList.size());
            }
//            data.getRecords().sort(Comparator.comparing(Manager::getMgId).reversed());
            resultMap = ResultUtils.resultMap("0", "success", data);
            logger.info("==>ManagerController--selectManagerList--over,result is{}", resultMap);
        } catch (NumberFormatException nfe) {
            resultMap = ResultUtils.resultMap("-1", "入参类型有误", null);
            logger.info("==>ManagerController--selectManagerList--NumberFormatException,result is{}", resultMap);
        } catch (Exception e) {
            resultMap = ResultUtils.resultMap("-1", "系统异常", null);
            logger.info("==>ManagerController--selectManagerList--Exception,result is{}", resultMap);
        }
        return resultMap;
    }

    /**
     * 更新管理员状态
     *
     * @param inMap
     * @return resultMap
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateStatus(@RequestBody Map<String, Object> inMap) {
        logger.info("==>ManagerController--updateStatus()--start, param is: {}", inMap);
        Manager manager = new Manager();
        Map<String, Object> resultMap;
        try {
            if (MapUtils.isEmpty(inMap) || null == inMap.get("mgId") ||
                    null == inMap.get("mgState")) {
                return ResultUtils.resultMap("-1", "param is error", null);
            }
            int mgState = Integer.parseInt(inMap.get("mgState").toString());
            if (0 != mgState && 1 != mgState) {
                return ResultUtils.resultMap("-1", "mgState is error", null);
            }
            manager.setMgState(mgState);
            manager.setMgId(Integer.parseInt(inMap.get("mgId").toString()));
            if (StringUtils.isNotBlank((String) inMap.get("mgPwd"))) {
                manager.setMgPwd((String) inMap.get("mgPwd"));
            }
            if (StringUtils.isNotBlank((String) inMap.get("mgEmail"))) {
                manager.setMgEmail((String) inMap.get("mgEmail"));
            }
            if (StringUtils.isNotBlank((String) inMap.get("mgMobile"))) {
                manager.setMgMobile((String) inMap.get("mgMobile"));
            }
            boolean b = managerService.updateById(manager);
            if (b) {
                Manager data = managerService.getBaseMapper().selectById((Integer) inMap.get("mgId"));
                return ResultUtils.resultMap("0", "success", data);
            }
            resultMap = ResultUtils.resultMap("-1", "更新失败", null);
        } catch (NumberFormatException ne) {
            logger.error("==>ManagerController--updateStatus()--NumberFormatException: {}", ne.getMessage());
            resultMap = ResultUtils.resultMap("-1", "输入类型有误", null);
        } catch (Exception e) {
            logger.error("==>ManagerController--updateStatus()--Exception: {}", e);
            resultMap = ResultUtils.resultMap("-1", e.toString(), null);
        }
        return resultMap;
    }

    /**
     * 添加管理员新账号
     */
    @PostMapping("/insert")
    @ResponseBody
    public Map<String, Object> insertManagerInfo(@RequestBody Manager manager) {
        try {
            if (StringUtils.isBlank(manager.getMgName())
                    || StringUtils.isBlank(manager.getMgPwd())) {
                return ResultUtils.resultMap("-1", "用户名或密码为空", null);
            }
            manager.setRoleId(100);
            manager.setMgTime((int) System.currentTimeMillis());
            int i = managerService.getBaseMapper().insert(manager);
            if (i > 0) {
                return ResultUtils.resultMap("0", "success", null);
            }
        } catch (Exception e) {
            logger.error("==>ManagerController--insetManagerInfo--Exception is: {}", e);
        }
        return ResultUtils.resultMap("-1", "添加用户失败", null);
    }

    /**
     * 删除管理员
     *
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    public Map<String, Object> deleteById(@RequestParam("mgId") String mgId) {
        try {
            if (null == mgId) {
                return ResultUtils.resultMap("-1", "入参为空", null);
            }
            boolean b = managerService.removeById(mgId);
            if (!b) {
                return ResultUtils.resultMap("-1", "删除失败", null);
            }
            return ResultUtils.resultMap("0", "success", null);
        } catch (Exception e) {
            logger.error("==>managerController--deleteById--Exception is : {}", e);
            return ResultUtils.resultMap("-1", "系统异常", null);
        }
    }
}

